/*模拟PHP的GET , 使用时, 可以直接 $_GET['get参数'], 就直接获得GET参数的值*/
var $_GET = (function () {
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if (typeof (u[1]) == "string") {
        u = u[1].split("&");
        var get = {};
        for (var i in u) {
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();

/**
 * Created by wuye on 2017/12/11.
 */

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el: '#rrapp',
    data: {
        inputs: [{
                sectionname: null,
                checkbox: false
            },
            {
                sectionname: null,
                checkbox: false
            },
            {
                sectionname: null,
                checkbox: false

            },
            {
                sectionname: null,
                checkbox: false

            },
            {
                sectionname: null,
                checkbox: false

            },
            {
                sectionname: null,
                checkbox: false

            },
            {
                sectionname: null,
                checkbox: false

            },
            {
                sectionname: null,
                checkbox: false

            }, {
                sectionname: null,
                checkbox: false

            }, {
                sectionname: null,
                checkbox: false

            }, {
                sectionname: null,
                checkbox: false

            },
        ],

        // 缓存要修改的章节信息
        updateSectionInfo: {

        },
        // 缓存要修改的卷信息
        updateVolumeInfo: {
            volumeName:null,
            id:null,
        },

        showVolume:false,
        // 显示添加章节的dom节点
        showDom: 'list',
        bookinfo: {
            bookname: '加载中'
        },
        q: {
            bookname: null
        },
        showList: true,
        title: null,
        // roleList:{},
        banner: {
            bannerpic: null
        },
        sels: [

        ],
        editor:null,
        minutes:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
        seconds:[0,15,30,45],
        userDate:null,
        userTime:null,
        otherWord:null,
        selectMin:0,
        selectSec:0,
        choseCheckBox:false,
        showChoseDate:null,
        updateOrNot:false,
        sectionBook:{},
    },
    created: function () {
        // 获取id
        var bookID = $_GET['id'];
        var isEdit=$_GET['edit'];
        if (!bookID) {
            alert('系统错误,没有获取到书籍ID,请返回重试.');
            return false;
        }
        if(isEdit){
            this.$nextTick(function(){
                this.addsection2()
            })

        }
        console.log(bookID, 'bokid');

        $.get(baseURL + "sys/book/findById/" + bookID, function (r) {
            vm.bookinfo = r.book;
        });
        $.get(baseURL + "sys/volume/findByBookId/" + bookID, function (r) {
            vm.sels = r.list;
        });

        // 加载章节列表

        $(function () {
            $("#jqGrid").jqGrid({
                mtype: 'POST',
                url: baseURL + 'sys/section/findAllByCondition',
                datatype: "json",
                colModel: [{
                        label: 'ID',
                        name: 'id',
                        index: "id",
                        width: 45,
                        key: true
                    },
                    {
                        label: '章节名称',
                        name: 'sectionname',
                        width: 75
                    },
                    {
                        label: '价格(蝉币)',
                        name: 'totalfee',
                        width: 75,
                        formatter: function (value, options, row) {
                            return value / 100
                        }
                    },
                    {
                        label: '字数',
                        name: 'fontsize',
                        width: 75
                    },
                    {
                        label: '章节类型',
                        name: 'sectionType',
                        width: 75,
                        formatter: function(value, options, row) {
                            if (value === 0) {
                                return '<span class="label label-primary">免费</span>';
                            }
                            if (value === 1) {
                                return '<span class="label label-success">付费</span>';
                            }
                        }
                    },
                    {
                        label: '发布类型',
                        name: 'sectionStatus',
                        width: 75,
                        formatter: function(value, options, row) {
                            if (value === 0) {
                                return '<span class="label label-primary">已发布</span>';
                            }
                            if (value === 1) {
                                return '<span class="label label-success">待发布</span>';
                            }
                        }
                    },
                    {
                        label: '所属卷',
                        name: 'volumeName',
                        width: 75
                    },
                    {
                        label: '创建时间',
                        name: 'createdate',
                        width: 90
                    },
                    {
                        label: '更新时间',
                        name: 'updatedate',
                        width: 90
                    },
                    {
                        label: '更新人',
                        name: 'updateuser',
                        width: 80
                    },
                    {
                        label: '上传人',
                        name: 'createuser',
                        index: "createuser",
                        width: 90
                    }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList: [10, 30, 50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth: true,
                multiselect: true,
                pager: "#jqGridPager",
                jsonReader: {
                    root: "page.records",
                    page: "page.current",
                    total: "page.pages",
                    records: "page.total"
                },
                prmNames: {
                    page: "page",
                    rows: "limit",
                    order: "order",
                },
                postData: {
                    bookid: bookID
                },
                gridComplete: function () {
                    //隐藏grid底部滚动条
                    $("#jqGrid").closest(".ui-jqgrid-bdiv").css({
                        "overflow-x": "hidden"
                    });
                }
            });
        });
    },
    mounted(){

    },
    methods: {
        // 选中年月日
        getDate:function(val){
        this.choseCheckBox=false
            var this_time=$('input[name="choseDate"]').val();
            var this_datetime=new Date(this_time);
            this.userDate=this_time
        },
        // checkBox事件
        decition:function(){
            var minTransform=''
          this.choseCheckBox=!this.choseCheckBox
            if(this.choseCheckBox){
              if(this.userDate&&this.selectMin){
                  if(!this.selectSec){
                      this.selectSec=this.selectSec+'0'
                      console.log(this.selectSec)
                  }
                  if(this.selectMin.length<2){
                      minTransform='0'+this.selectMin
                  }else {
                      minTransform=this.selectMin
                  }
                  var decideDate=this.userDate+' '+minTransform+':'+this.selectSec+':00'
                  if(Date.parse(new Date())<Date.parse(new Date(decideDate))){
                      this.showChoseDate=decideDate
                  }else {
                      alert('定时发布时间需大于当前时间');
                      this.choseCheckBox=false
                  }
              }else {
                  alert('请输入定时发布完整时间');
                  this.choseCheckBox=false
              }
            }
        },
        getFile: function (e) {

            var file = e.target.files[0]
            var reader = new FileReader()
            var THIS = this
            reader.readAsDataURL(file)
            reader.onload = function (e) {
            //     // this.result 为图片
            //     var fileData = this.result;
            //     THIS.section.filetext = fileData
                // console.log(THIS.section.filetext,'lllllllll');
            }

        },
        // 选中卷
        changeVolume:function(sel){
          this.updateVolumeInfo.id=sel.id
          this.updateVolumeInfo.volumeName=sel.volumeName;
          this.updateSectionInfo.volumeId=sel.id
          this.showVolume=false
        },
        // 弹出新建卷
        showAddVolume:function(){
            this.showVolume=false
            var THIS=this
            layer.prompt({title: '请填写卷名', formType: 2}, function(pass, index){
                layer.close(index);
                THIS.submitFormVolume(pass)
            });
        },
        backToBook:function(){
            $.ajax({
                type: "POST",
                url: baseURL + "sys/user/info",
                success: function(r){
                    if(r.user.identity){
                        window.location.href='authorBook.html'
                    }else{
                        window.location.href='book.html'
                    }
                    vm.updateOrNot=false;
                }
            });


        },
        getFileUpdateSection: function (e) {
            var file = e.target.files[0]
            var reader = new FileReader()
            var THIS = this
            reader.readAsDataURL(file)
            reader.onload = function (e) {
                var fileDataUpdate = this.result;
                THIS.sectionFileDataUpdate.filetext = fileData
            }

        },
        submitForm: function (event) {
            event.preventDefault();
            // console.log(this);
            const _this = this;
            let arr=this.inputs
            console.log(arr)
            let newArr=[];
            let formArr=[]
            for (var one in arr) {
                // console.log(_this.inputs[one].sectionname)
                if (this.$refs['inputfile'][one].files[0] && arr[one].bookPrice) {
                    newArr.push(arr[one]);
                    console.log(newArr)
                    console.log(this.$refs['inputfile'][one].files[0]);
                    console.log(newArr[one]);
                    console.log(newArr[one]['volumeId'])

                    var sfile = new FormData()
                    sfile.append('filetext', this.$refs['inputfile'][one].files[0])
                    sfile.append('sectionname', newArr[one]['sectionname'])
                    sfile.append('bookid', vm.bookinfo.id);
                    // sfile.append('isPay', _this.inputs[one]['checkbox']);
                    sfile.append('bookPrice', newArr[one]['bookPrice']);
                    sfile.append('volumeId', newArr[one].volumeId);
                    sfile.append('id', '')
                    formArr.push(sfile)
                } else {
                    console.log('wuzhi')
                }

            }
            _this.ajaxLoop(1,formArr)
            return false;
        },
        ajaxLoop(index,arr){
            let THIS=this
            var index = layer.load(2, {shade: false});
            if(index<arr.length+1){
                console.log(index);
                $.ajax({
                    url: baseURL + '/sys/section/save',
                    // $refs: {'tdSection':vm.section,'filetext':this.section.filetext},
                    data: arr[index-1],
                    // headers: {
                    //"Content-Type": "multipart/form-$refs"
                    // "Content-Type": "text/plain;charset=UTF-8"
                    // },
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function (result) {
                        layer.closeAll('loading')
                        if (result.code === 0) {
                            THIS.ajaxLoop(index+1,arr);
                        } else {
                            alert(result.msg);
                        }
                    },
                })
            }else {
                layer.closeAll('loading')
                alert('添加成功!', function () {
                    window.location.reload();
                });
            }
        },
        // 添加卷
        submitFormVolume: function (name) {
            event.preventDefault();
            // console.log(this);
            const _this = this;
                var sfile = new FormData()
                sfile.append('volumeName', name)
                sfile.append('bookid', vm.bookinfo.id);
                sfile.append('id', '')
                $.ajax({
                    url: baseURL + '/sys/volume/save',
                    data: sfile,
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function (result) {
                        if(result.code === 0){
                            alert('添加成功!', function () {
                                $.get(baseURL + "sys/volume/findByBookId/" + _this.bookinfo.id, function (r) {
                                    vm.sels = r.list;
                                });
                            });
                        }else {
                            alert(result.msg);
                        }
                    },
                    // error: function (error) {
                    //     alert('添加失败!');
                    // }
                })
            return false;
        },
        submitFormUpdateSection2: function (event) {

            var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

            event.preventDefault();
            let data=Base64.encode(vm.editor.txt.html());
            const _this = this;
            let leadWordBefore='<p>---------------------</p><p>作者寄语：</p><p>'+_this.otherWord+'<p>'
            let leadWord=Base64.encode(leadWordBefore)
            console.log(vm.bookinfo)
            var sfile = new FormData()
            sfile.append('text1', data)
            sfile.append('sectionname', _this.updateSectionInfo.sectionname)
            sfile.append('bookid', vm.bookinfo.id);
            if(_this.otherWord){
                sfile.append('leadStr', leadWord);
            }else {
                sfile.append('leadStr', '');
            }
            sfile.append('volumeId', _this.updateSectionInfo.volumeId);
            if(_this.choseCheckBox&&_this.showChoseDate){
                console.log('in')
                sfile.append('publishTime', _this.showChoseDate);
            }else {
                sfile.append('publishTime', '');
            }
            var psw=sfile.get('publishTime');
            console.log(psw)
            confirm('确定提交？', function () {
                $.ajax({
                    url: baseURL + '/sys/section/saveByAuthor',
                    data: sfile,
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function (result) {
                        if(result.code == 0){
                            alert('修改成功!', function () {
                                var page = $("#jqGrid").jqGrid('getGridParam', 'page');
                                $("#jqGrid").jqGrid('setGridParam', {
                                    postData: {
                                        'bookname': vm.q.bookname
                                    },
                                    page: page
                                }).trigger("reloadGrid");
                                vm.showDom='list'
                            });

                        }else {
                            alert('添加失败!'+result.msg);
                        }
                    },
                    error: function (error) {
                        alert('添加失败!');
                    }
                })
            });
            return false;
        },

        submitFormUpdateSection: function (event) {
            event.preventDefault();
            // console.log(this);
            const _this = this;

            // console.log(_this.inputs[one].sectionname)

            var __file = this.$refs['updateSection'].files[0];

            var sfile = new FormData()
            sfile.append('filetext', __file)
            sfile.append('sectionname', _this.updateSectionInfo.sectionname)
            sfile.append('bookid', vm.bookinfo.id);
            sfile.append('bookPrice', _this.updateSectionInfo.totalfee);
            sfile.append('volumeId', _this.updateSectionInfo.volumeId);
            sfile.append('id', _this.updateSectionInfo.id)

            console.log(_this.updateSectionInfo)

            $.ajax({
                url: baseURL + '/sys/section/save',
                data: sfile,
                cache: false,
                processData: false,
                contentType: false,
                type: 'post',
                success: function (result) {
                    if(result.code == 0){
                        alert('修改成功!', function () {
                            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
                            $("#jqGrid").jqGrid('setGridParam', {
                                postData: {
                                    'bookname': vm.q.bookname
                                },
                                page: page
                            }).trigger("reloadGrid");
                            vm.showDom='list'
                        });
                    }else {
                        alert('修改失败!'+result.msg);                    
                    }
                },
                error: function (error) {
                    alert('修改失败!');
                }
            })



            return false;
        },
        addsection: function () {
            vm.showDom = 'addSec'

            var _thisID = $_GET['id'];
            vm.title = "添加章节";
        },
        addsection2: function () {
            var THIS=this
            THIS.showDom = 'addbook'
            var _thisID = $_GET['id'];
            THIS.title = "添加章节";
            var E = window.wangEditor
            var editor = new E('#editor','#typingLand')
            // 或者 var editor = new E( document.getElementById('editor') )
            editor.create()
            THIS.editor=editor;
        },
        back() {
            window.history.go(-1);
        },
        updateSectionBtn: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            var THIS=this
            THIS.title = "修改章节";
            var E = window.wangEditor
            var editor = new E('#editor','#typingLand')
            // 或者 var editor = new E( document.getElementById('editor') )
            editor.create();
            THIS.editor=editor;
            // 加载单条章节详情
            $.get(baseURL + "sys/section/findById/"+id, function(r){
                if(r.code==0){
                    $.get(baseURL + "sys/book/findById/" + r.map.section.bookid, function (res) {
                        vm.sectionBook = res.book;
                        $.ajax({
                            type: "POST",
                            url: baseURL + "sys/user/info",
                            success: function(result){
                                if(res.book.origin){
                                    if(!result.user.identity){
                                        alert('管理员只能修改本站书籍的章节信息')
                                    }else {
                                        THIS.$nextTick(function () {
                                            THIS.showDom = 'addbook'
                                            THIS.updateSectionInfo = r.map.section
                                            THIS.updateSectionInfo.totalfee = vm.updateSectionInfo.totalfee / 100
                                            THIS.updateOrNot=true;
                                            if(vm.updateSectionInfo.context){
                                                THIS.editor.txt.html(vm.updateSectionInfo.context)
                                            }else {
                                                THIS.editor.txt.html('')
                                            }

                                        })
                                    }

                                }else {
                                    THIS.updateSectionInfo = r.map.section
                                    THIS.updateSectionInfo.totalfee = vm.updateSectionInfo.totalfee / 100
                                    THIS.showDom='update'
                                }
                                vm.updateOrNot=false;
                            }
                        });
                    });

                }else {
                    alert('请求失败!');
                }


            });
        },
        // 修改章节
        updateSectionInSame:function(){
            var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

            event.preventDefault();
            let data=Base64.encode(vm.editor.txt.html());
            const _this = this;
            var sfile = new FormData()
            console.log(vm.bookinfo.id,_this.updateSectionInfo.sectionname)
            sfile.append('text1', data)
            sfile.append('id', _this.updateSectionInfo.id)
            sfile.append('sectionname', _this.updateSectionInfo.sectionname)
            sfile.append('bookid', vm.bookinfo.id);
            confirm('确定提交？', function () {
                $.ajax({
                    url: baseURL + '/sys/section/update',
                    data: sfile,
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function (result) {
                        if(result.code == 0){
                            alert('修改成功!', function () {
                                var page = $("#jqGrid").jqGrid('getGridParam', 'page');
                                $("#jqGrid").jqGrid('setGridParam', {
                                    postData: {
                                        'bookname': vm.q.bookname
                                    },
                                    page: page
                                }).trigger("reloadGrid");
                                vm.showDom='list'
                            });
                        }else {
                            alert('修改失败!'+result.msg);
                        }
                    },
                    error: function (error) {
                        alert('修改失败!');
                    }
                })
            });




            return false;
        },
        getBook: function (id) {
            $.get(baseURL + "sys/book/findById/" + id, function (r) {
                console.log(r)
                vm.sectionBook = r.book;
            });
        },
        del: function () {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/section/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function () {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'bookname': vm.q.bookname
                },
                page: page
            }).trigger("reloadGrid");
        }
    }
});